import pathlib
import re

import meshio
import numpy as np

import maxwell2gmsh


class Point2D:
    def __init__(self):
        self.x = 0
        self.y = 0
        self.i = 0
        self.j = 0


def read_dsp(filename):
    mesh_data = {}
    element_pattern = r'\s+(\w+)\((.*)\)'
    pathfile = pathlib.Path(filename)
    types = ['Elements', 'Nodes', 'ElemSolution']
    txt = pathfile.read_text().split('\n')
    for line in txt:
        match = re.match(element_pattern, line)
        if match:
            var_type = match.group(1)
            mesh_data[var_type] = [float(dat) for dat in match.group(2).split(',')]

    return mesh_data


if __name__ == '__main__':
    data = read_dsp(filename='data/motor.dsp')
    elements = data['Elements']
    num_nodes = int(elements[0])
    num_elements = int(elements[1])
    cell_type = 'triangle6'
    element_orders = np.array(elements[2:]).reshape(int((len(elements) - 2) / 11), 11)[:, 5:]
    nodes = np.array(data['Nodes'])
    nodes = nodes.reshape((int(nodes.size / 3), 3))
    cells = {}
    cells[cell_type] = maxwell2gmsh.mxwl2gmsh(element_orders)
    meshio.write_points_cells('motor.vtk', nodes, cells)
